import React, { useState, useMemo, useCallback, useEffect, useRef, useReducer } from "react";
import { render } from "react-dom";
import { Table } from "antd";
import { VList } from "./virtualAntd.less.tsx";

import "./styles.css";

const columns: any = [
  {
    title: "序号",
    key: "id",
    fixed: "left",
    render(text, record, index) {
      return index + 1;
    },
    width: 100
  }
];

for (let i = 0; i < 100; i += 1) {
  columns.push({
    title: `公司${i + 1}`,
    dataIndex: `company_name${i + 1}`,
    width: i % 2 === 0 ? 100 : 120,
    // render: () => {
    //   return `I am doing test.${i + 1}`
    // }
  });
}

const generateData = () => {
  let tempDataSource: any[] = [];
  for (let i = 0; i < 400; i++) {
    let obj: any = {
      company_name: `company_name${i}`
    };
    columns.forEach((c, index) => {
      obj[c.dataIndex] = `${i}-${index} 我唱的不够动人 你别皱眉`;
    });

    tempDataSource.push(obj);
  }

  tempDataSource[0].children = [{
    company_name: '111111',
    company_name0: '000000',
    company_name1: '111111',
    company_name2: '222222',
    company_name3: '333333',
    company_name4: '444444',
    company_name5: '555555',
    company_name6: '666666',
  }]

  return tempDataSource;
};

function App() {
  const [finalColumns, setFinalColumns] = useState(columns);
  const [dataSource, setDataSource] = useState(generateData());

  const [loading, setLoading] = useState(false);

  const handleReachEnd = useCallback(() => {
    setLoading(true);
    console.log("执行了");
    setDataSource((pre) => {
      const temp = generateData();
      return [...pre, ...temp];
    });
    setFinalColumns(prev => [...prev.slice(0, 3), {
      title: '插入',
      dataIndex: 'company_namecompany_name',
      width: 250,
      render: (_, record) => `${record.company_name + record.company_name}`
    }, ...prev.slice(3)])
    setTimeout(() => {
      setLoading(false);
    }, 1000);
  }, []);

  const [windowSize, setWindowSize] = useState({ width: window.innerWidth, height: window.innerHeight })
  useEffect(() => {
    const handleResize = () => {
      setWindowSize({ width: window.innerWidth, height: window.innerHeight })
    }
    window.addEventListener('resize', handleResize);

    const logSpendTime = () => {
      window.console.time('spendTime==>');
      window.requestIdleCallback(() => {
        window.console.timeEnd('spendTime==>');
      });
    }
    window.addEventListener('click', logSpendTime, true);
    return () => {
      window.removeEventListener('resize', handleResize);
      window.removeEventListener('click', logSpendTime);
    }
  }, [])

  const vc = useMemo(() => {
    return VList({
      scrollY: 500,
      scrollX: windowSize.width - 15,
      rowHeight: 48,
    });
  }, [windowSize, finalColumns]);

  // const refCounter = useRef(0);
  // const refQueue = useRef([]);

  return (
    <>
      <div className="virtualNext">
        <Table
          columns={finalColumns}
          dataSource={dataSource}
          pagination={false}
          loading={loading}
          scroll={{ y: 500 }}
          rowKey={"company_name"}
          components={vc}
          rowSelection={{
            columnWidth: 48,
          }}
        />
      </div>
      <br />
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={false}
        loading={loading}
        scroll={{ y: 500 }}
        rowKey={"company_name"}
        // components={{
        //   body: {
        //     wrapper: function VWrapper(props: any): JSX.Element {
        //       const { children, ...restProps } = props;

        //       window.console.log('===VWrapper==>', refCounter.current++);
        //       let computedChildren = children;
        //       // if (Array.isArray(children[1])) {
        //       //   computedChildren = [children[0], children[1].slice(0, 5)]
        //       // }
        //       return <tbody {...restProps}>{computedChildren}</tbody>;
        //     },
        //     row: function VRow(props: any): JSX.Element {
        //       // const { curTableWith, curScrollLeft, colWidths, maxFixedLeftIndex } = useContext(ScrollContext);
            
        //       const { children, ...restProps } = props;
            
        //       // 计算横向应该显示的 td
        //       // const computedChildren = useMemo(
        //       //   () =>
        //       //     !Array.isArray(children) || !(curTableWith || colWidths?.length)
        //       //       ? children
        //       //       : computeNextChildren(
        //       //           {
        //       //             curTableWith,
        //       //             curScrollLeft,
        //       //             colWidths,
        //       //             maxFixedLeftIndex,
        //       //           },
        //       //           children,
        //       //         ),
        //       //   [children, curTableWith, colWidths?.join(','), curScrollLeft, maxFixedLeftIndex],
        //       // );
            
        //       window.console.log('===computedChildren==>', refCounter.current++);

        //       const refNextProps = useRef(props);
        //       const [flag, reRun] = useReducer(x => !x, false);

        //       const jsx = useMemo(() => {

        //         return <tr {...restProps}>{children}</tr>;
        //       }, [flag, props]);
            
        //       return jsx;
        //     },
        //   }
        // }}
        rowSelection={{}}
      />
    </>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);
// createRoot(rootElement!).render(<App />);

